<?php
/**
 * @copyright 2008 cryonyx
 */

//	Reference to VC_DB interface
require(dirname(__FILE__) . '/core/vc.db.php');

//	Initialize class for WP based on interface WP_DB.
class VC_DB_WP extends WPDB implements VC_DB {
	public function fetch_stat($id) {
		return array(
			'views'	=>	3156,
			'visitors'	=>	'098765432198iirhd~!@""""',
			'latest_view'	=>	'2007-12-11 10:38:14'
		);	
	}
	
	public function store_stat($id, $stat) {
		return TRUE;
	}
	
	public function fetch_options($option = NULL) {
		
	}
	
	public function store_options(Array $options) {
		
	}
	
	/**
	 * Updates database from version 0.1 to 1.0
	 * 
	 * @return boolean
	 */
	public function migrate_database() {
		/*if($_SESSION['vc']['migrated']) {
			return TRUE;
		}*/
		
		//	Importing existing statistics data
		$query	=	<<<SQL
SELECT * FROM `{$table_prefix}vc_data`;
SQL;
		//	Use function get_results() of WPDB class
		$raw_data		=	self::get_results($import_query);
		trigger_error('Hey! Im here!!! ' . print_r($raw_data, TRUE), E_USER_NOTICE);
		
		if(	is_array($raw_data)	&&
			!empty($raw_data)
		) {
		//	Processing existing data
		foreach($raw_data as $entry) {
			//	Get identifier of the entry
			$id		=	$entry->id;
			//	Get encoded views and visitors data
			list($views, $visitors_raw)	=	explode('/', $entry->data);
			//	Decode views
			$views	=	hexdec($views);
			//	For each visitor convert statistics into new format
			foreach($visitors_raw as &$visitor) {
				$visitor	=	implode(			//	Glue chunks alltogether
					array_map('chr',				//	Transform each chunk into a character
						array_map('hexdec',			//	Each chunk convert to a decimal
							str_split($visitor, 2)	//	Split a string like '42F948CF' into four chunks
						)
					)
				);
			}
			//	Implode all encoded chunks of statistics into one string
			$visitors	=	implode($visitors_raw);
			
			//	Insert the entry into new table
			$query	=	<<<SQL
INSERT INTO `{$table_prefix}vc_forrest` (`id`, `views`, `visitors`)
VALUES (%d, %d, %s);
SQL;
			//	Prepare the query to protect DB from SQL-injections
			$query	=	self::prepare($query, $id, $views, $visitors);
			//	Store the entry into database
			self::query($query);
			
			//	Delete the entry from old statistics table
			/*$query	=	<<<SQL
DELETE FROM `{$table_prefix}vc_data` WHERE `id`='{$id}';
SQL;
			//	Process the query
			self::query($query);*/
		}
		}
		
		//	Drop old data table
		/*$query	=	<<<SQL
DROP TABLE `{$table_prefix}_vc_data`;
SQL;
		self::query($query);*/
		
		//	Mark that the database is migrated
		$_SESSION['vc']['migrated']	=	TRUE;
		self::store_options(array('migrated' => TRUE));
		
		//	Succesfully terminate the migration
		return TRUE;
	}
	
}
?>